package org.dylan.evernote;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.MultiHashMap;
import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.map.MultiValueMap;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.dylan.keepnote.KNote;
import org.dylan.keepnote.KNoteExtractor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.evernote.edam.error.EDAMNotFoundException;
import com.evernote.edam.error.EDAMSystemException;
import com.evernote.edam.error.EDAMUserException;
import com.evernote.edam.notestore.NoteFilter;
import com.evernote.edam.notestore.NoteList;
import com.evernote.edam.type.Note;
import com.evernote.edam.type.Notebook;
import com.evernote.edam.type.Resource;
import com.evernote.edam.type.Tag;
import com.evernote.thrift.TException;

/**
 * 
 * 
 * @Copyright: Copyright (c) 2013 FFCS All Rights Reserved
 * @Company: 北京福富软件有限公司
 * @author 陈作朋 Nov 1, 2013
 * @version 1.00.00
 * @history:
 * 
 */
public class ListNote {

	private final static Logger failedLogger = LoggerFactory.getLogger("ktoe.failed");
	
	private final static Logger notebookLogger = LoggerFactory.getLogger("ktoe.notebook");
	
	private final static Logger successLogger = LoggerFactory.getLogger("ktoe.success");

	public static Map<String, String> getTags(EDAMContext context) throws EDAMUserException, EDAMSystemException, TException {
		Map<String, String> result = new HashMap<String, String>();
		List<Tag> tags = context.getNoteStore().listTags();
		System.out.println("tags size:" + tags.size());
		for (Tag tag : tags) {
			result.put(tag.getGuid(), tag.getName());
			// failedLogger.info(tag.getGuid()+" : "+tag.getName());
		}
		return result;
	}

	public static List<String> getTagOfNote(Map<String, String> tags, List<String> tagGuids) {
		List<String> result = new ArrayList<String>();
		for (String tg : tagGuids) {
			if (tags.containsKey(tg)) {
				result.add(tags.get(tg));
			}
		}
		return result;
	}

	public static void getNoTagsOfNotes() throws Exception {
		EDAMContext context = new EDAMContext();

		/*
		 * List<Notebook> notebooks = context.getNoteStore().listNotebooks();
		 * System.out.println("size:" + notebooks.size()); for (Notebook
		 * notebook : notebooks) { System.out.println(notebook); }
		 */

		// K-Linux guid: 25bb48fc-85d3-45fe-abe1-1280b57266cd

		Map<String, String> tags = getTags(context);

		final String nbGuid = "25bb48fc-85d3-45fe-abe1-1280b57266cd";

		int totalNotes = context.getNoteStore().findNotes(new NoteFilter() {
			{
				setNotebookGuid(nbGuid);
			}
		}, 0, 1).getTotalNotes();

		System.out.println("total:" + totalNotes);

		int offset = 0;

		int count = 0;
		int j = 0;
		do {
			NoteList noteList = context.getNoteStore().findNotes(new NoteFilter() {
				{
					setNotebookGuid(nbGuid);
				}
			}, offset, 50);

			int currPageSize = noteList.getNotesSize();

			System.out.println("curr size:" + currPageSize);

			for (Note note : noteList.getNotes()) {
				List<String> tagsOfNote = getTagOfNote(tags, note.getTagGuids());

				if (tagsOfNote.size() == 1 && tagsOfNote.contains("KeepNote")) {
					System.out.println(note.getTitle() + "[" + note.getGuid() + "]:" + getTagOfNote(tags, note.getTagGuids()));
					failedLogger.info(note.getTitle() + " : " + note.getGuid());
					j++;
				}
				count++;
			}

			offset += 50;

		} while (offset < totalNotes);

		System.out.println("count:" + count);
		System.out.println("j:" + j);
	}

	static int knoteCount = 0;

	public static void handleNote(EDAMContext context, Map<String, String> tags, KNote knote) throws Exception {
		if (!knote.isNoteDir()) {

			if (null == knote.getContent()) {
				System.out.println("======= content is empty - path:" + knote.getPath() + ",title:" + knote.getTitle());
				return;
			}

			if (!tags.values().contains(knote.getName())) {
				System.out.println(knote.getName() + ":" + knote.getTitle());
				knoteCount++;
			}
		}

		List<KNote> childs = knote.getChilds();
		for (KNote cknote : childs) {
			handleNote(context, tags, cknote);
		}

	}

	public static Map<String, String> loadTags() throws Exception {
		Map<String, String> tags = new HashMap<String, String>();

		List<String> list = FileUtils.readLines(new File("logs//failed.2013-11-01.log"));
		for (String string : list) {
/*			String[] tmp = string.split(" - ");
			String[] tmp2 = tmp[1].trim().split(" : ");*/
			
			String tmp=string.substring(string.indexOf(" - ")+3);
			
			String[] tmp2 = tmp.trim().split(" : ");
			
//			System.out.println("--" + tmp[1]);
			tags.put(tmp2[1].trim(), tmp2[0].trim());
		}
		System.out.println("---:" + tags);
		return tags;
	}

	public static Map<String, String> loadNoTagOfNote() throws Exception {
		Map<String, String> notes = new HashMap<String, String>();

		List<String> list = FileUtils.readLines(new File("logs//failed.2013-11-02.log"));
		for (String string : list) {
			String[] tmp = string.split(" : ");
			// String[] tmp2=tmp[1].trim().split(" : ");
			notes.put(tmp[0].trim(), tmp[1].trim());
		}
		System.out.println("+++:" + notes);
		return notes;
	}

	public static Set<String> loadNoRepeatTags() throws Exception {
		Set<String> set = new HashSet<String>();
		Map<String, String> tags = loadTags();

		Set<String> keys = tags.keySet();

		for (String key : keys) {
			System.out.println("===" + key);
			if (key.contains("(")) {
				set.add(key.substring(0, key.lastIndexOf("(")));
			} else {
				System.out.println("***:" + key);
			}
		}
		System.out.println(set);
		return set;
	}
	
	public static MultiMap loadMultiMapTags() throws Exception {
		MultiMap multiMap=new MultiValueMap();
		Map<String, String> tags = loadTags();

		Set<String> keys = tags.keySet();

		for (String key : keys) {
			String tmp=key;
			if (key.contains("(")) {
				tmp=key.substring(0, key.lastIndexOf("("));
			} else {
				System.out.println("***:" + key);
			}
			List<String> values=new ArrayList<String>();
			values.add(key);
			values.add(tags.get(key));
			multiMap.put(tmp,values);
		}
		System.out.println(multiMap);
		return multiMap;
	}
	
	public static void updateTagToNote(EDAMContext context,String guid,String tagName) throws EDAMUserException, EDAMSystemException, EDAMNotFoundException, TException{
	    Note note = context.getNoteStore().getNote(guid, true, true, false, false);

	    // Do something with the note contents or resources...

	    // Now, update the note. Because we're not changing them, we unset
	    // the content and resources. All we want to change is the tags.
	    note.unsetContent();
	    note.unsetResources();

	    // We want to apply the tag "TestTag"
	    note.addToTagNames(tagName);

	    // Now update the note. Because we haven't set the content or resources,
	    // they won't be changed.
	    context.getNoteStore().updateNote(note);
	    System.out.println("Successfully added tag to existing note");
	}

	public static void main(String[] args) throws Exception {
		EDAMContext context = new EDAMContext();

		// 396
		// test1();

		/*
		 * List<Notebook> notebooks = context.getNoteStore().listNotebooks();
		 * System.out.println("size:" + notebooks.size()); for (Notebook
		 * notebook : notebooks) { System.out.println(notebook); }
		 */

		// K-Linux guid: 25bb48fc-85d3-45fe-abe1-1280b57266cd

		// 395

		/*
		 * Map<String, String> tags = getTags(context);
		 * 
		 * KNoteExtractor.seq = 607; String path = "/home/dylan/Data/n/Java/";
		 * 
		 * KNote knote = KNoteExtractor.extract(path);
		 * System.out.println("extract KeepNote completed"); handleNote(context,
		 * tags, knote); System.out.println("knoteCount:" + knoteCount);
		 */

		// test1();

//		 Map<String,String> tags=loadTags();

//		Set<String> noRepeatTags = loadNoRepeatTags();
//		System.out.println(noRepeatTags.size());
		
/*		Map<String,String> noTagsOfNotes=loadNoTagOfNote();
		 
		MultiMap multiMap=loadMultiMapTags();
		
		for (String note : noTagsOfNotes.keySet()) {
			System.out.println("&&&&&:"+note);
			List list=(List)multiMap.get(note);
			
			if(list==null){
				successLogger.info(note+":"+noTagsOfNotes.get(note));
			}else if (list.size() == 1) {
				String guid=noTagsOfNotes.get(note);
				String tagName=((List<String>)list.get(0)).get(0);
				
				System.out.println(guid+" --- "+tagName);
				
				updateTagToNote(context, guid, tagName);
			}else{
				notebookLogger.info("note[{},{}] - list:{}",note,noTagsOfNotes.get(note),list);
			}
		}*/
		
		getNoTagsOfNotes();
		
/*		Set<String> keys=multiMap.keySet();
		int i=0;
		for (String key : keys) {
        	List<String> list=(List<String>)multiMap.get(key);
			if (list.size() > 1) {
				System.out.println("$$$$ - " + key + ":" + list);
				i++;
			}
		}
		System.out.println("i="+i);*/
		
/*		String str="2013-11-01 23:55:02.296 - 335db89a-b655-46ef-a37e-5ada655b3b6d : LVM - 很好很强大(15)";
		System.out.println(str.substring(str.indexOf(" - ")+3));*/

	}
}
